<template>
  <div class="admin-info">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">

      <el-form-item label="站点">
        <el-select v-model="searchForm.siteId" placeholder="请选择站点" clearable>
          <el-option
            v-for="site in siteOptions"
            :key="site.id"
            :label="site.siteName"
            :value="site.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchAdminInfo">查询</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 管理员信息表格 -->
    <el-table :data="adminInfoList" style="width: 100%" class="admin-table">
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
      <el-table-column label="角色" width="120">
        <template #default="scope">
          {{ formatRole(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          {{ formatState(scope.row.state) }}
        </template>
      </el-table-column>
      <el-table-column prop="siteId" label="站点ID" width="100"></el-table-column>
      <el-table-column prop="username" label="账号" min-width="120"></el-table-column>
      <el-table-column label="过期时间" min-width="180">
        <template #default="scope">
          {{ scope.row.expireTime ? scope.row.expireTime : '无限期' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination-container"
    ></el-pagination>

    <!-- 新增信息对话框 -->
    <el-dialog
      title="新增工作人员"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handleAddDialogClose"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站点" prop="siteId">
          <el-select
            v-model="addForm.siteId"
            placeholder="请选择站点"
            :disabled="addForm.role === 4"
          >
            <el-option
              v-for="site in siteOptions"
              :key="site.id"
              :label="site.siteName"
              :value="site.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="addForm.expireTime"
            type="date"
            placeholder="选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改信息对话框 -->
    <el-dialog
      title="修改工作人员信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="handleEditDialogClose"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站点" prop="siteId">
          <el-select
            v-model="editForm.siteId"
            placeholder="请选择站点"
            :disabled="editForm.role === 4"
          >
            <el-option
              v-for="site in siteOptions"
              :key="site.id"
              :label="site.siteName"
              :value="site.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="editForm.expireTime"
            type="date"
            placeholder="选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import qs from 'qs';

export default {
  data() {
    return {
      originalRole: null,
      searchForm: {
        adminId: '',
        siteId: '',
        state: ''
      },
      adminInfoList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      roleOptions: [
        { value: 1, label: '管理员' },
        { value: 2, label: '负责人' },
        { value: 3, label: '临时工' },
        { value: 4, label: '客服' }
      ],
      filteredRoleOptions: [], // 新增: 动态过滤后的角色选项
      siteOptions: [], // 站点选项列表
      stateMap: {
        1: '空闲',
        2: '工作中',
        3: '异常'
      },
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        adminId: '',
        name: '',
        phone: '',
        role: 4,
        siteId: '',
        state: '1',
        expireTime: '',
        username: ''
      },
      editForm: {
        adminId: '',
        name: '',
        phone: '',
        role: '',
        siteId: '',
        state: '',
        expireTime: '',
        username: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        siteId: [

        ],
        state: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    clearSiteId() {
      this.editForm.siteId = null;
    },
    formatRole(role) {
      const roleObj = this.roleOptions.find(r => r.value === role);
      return roleObj ? roleObj.label : role;
    },
    formatState(state) {
      return this.stateMap[state] || state;
    },
    searchAdminInfo() {
      const params = {
        adminId: this.searchForm.adminId,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        siteId: this.searchForm.siteId,
        state: this.searchForm.state
      };

      axios.get('/zsd-permission/admin-info/selAdminInfoById', {
        params
      }).then(response => {
        const data = response.data.data;
        // 过滤掉超级管理员
        this.adminInfoList = data.list.filter(admin => admin.role !== 0);
        this.total = data.total;
      }).catch(error => {
        console.error('查询失败', error);
        this.$message.error('查询失败');
      });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.searchAdminInfo();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.searchAdminInfo();
    },
    handleAdd() {
      this.addForm = {
        adminId: '',
        name: '',
        phone: '',
        role: 4,
        siteId: '',
        state: '1',
        expireTime: '',
        username: ''
      };
      this.addDialogVisible = true;
    },
    handleEdit(row) {
      this.editForm = {
        adminId: row.adminId,
        name: row.name,
        phone: row.phone,
        role: row.role,
        siteId: row.siteId,
        state: row.state,
        expireTime: row.expireTime,
        username: row.username
      };
      this.originalRole = row.role;
      this.editDialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该工作人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/zsd-permission/admin-info/deleteAdminInfoById', {
          params: {
            adminId: row.adminId
          },
          headers: {
            'token': localStorage.getItem('token')
          }
        }).then(response => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.searchAdminInfo();
          } else {
            this.$message.error(response.data.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除失败', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleAddDialogClose() {
      this.$refs.addFormRef.resetFields();
      this.addForm = {
        adminId: '',
        name: '',
        phone: '',
        role: 4,
        siteId: '',
        state: '1',
        expireTime: '',
        username: ''
      };
    },
    handleEditDialogClose() {
      this.$refs.editFormRef.resetFields();
      this.editForm = {
        adminId: '',
        name: '',
        phone: '',
        role: '',
        siteId: '',
        state: '',
        expireTime: '',
        username: ''
      };
    },
    submitEdit() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          // 获取目标角色的当前值和新值
          const currentRole = this.originalRole; // 目标角色的当前值
          const targetRole = this.editForm.role; // 用户选择的新值

          // 判断目标角色的修改规则
          if ((currentRole === 1 || currentRole === 2) && (targetRole === 3 || targetRole === 4)) {
            this.$message.error('不可被更改');
            return;
          }

          if (currentRole === 3 && targetRole === 4) {
            this.$message.error('不可被更改');
            return;
          }

          // 创建表单数据对象
          const formData = {
            adminId: this.editForm.adminId,
            name: this.editForm.name,
            phone: this.editForm.phone,
            role: this.editForm.role,
            siteId: this.editForm.siteId || null,
            state: this.editForm.state,
            expireTime: this.editForm.expireTime ? this.editForm.expireTime.toISOString().split('T')[0] : null,
            username: this.editForm.username
          };

          // 发送请求
          axios({
            method: 'post',
            url: '/zsd-permission/admin-info/updateAdminInfo',
            data: formData,
            headers: {
              'Content-Type': 'application/json',
              'token': localStorage.getItem('token')
            }
          }).then(response => {
            if (response.data.code === 200) {
              this.$message.success('修改成功');
              this.editDialogVisible = false; // 关闭修改弹窗
              this.searchAdminInfo();
            } else {
              this.$message.error(response.data.msg || '修改失败');
            }
          }).catch(error => {
            console.error('修改失败', error);
            this.$message.error('修改失败');
          });
        }
      });
    },
    submitAdd() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          const formData = {
            name: this.addForm.name,
            phone: this.addForm.phone,
            role: this.addForm.role,
            siteId: this.addForm.siteId || null,
            state: this.addForm.state,
            expireTime: this.addForm.expireTime ? this.addForm.expireTime.toISOString().split('T')[0] : null,
            username: this.addForm.username
          };

          axios({
            method: 'post',
            url: '/zsd-permission/admin-info/insertAdminInfo',
            data: formData,
            headers: {
              'Content-Type': 'application/json',
              'token': localStorage.getItem('token')
            }
          }).then(response => {
            if (response.data.code === 200) {
              this.$message.success('添加成功');
              this.addDialogVisible = false; // 关闭新增弹窗
              this.searchAdminInfo();
            } else {
              this.$message.error(response.data.msg || '添加失败');
            }
          }).catch(error => {
            console.error('添加失败', error);
            this.$message.error('添加失败');
          });
        }
      });
    },
    handleAddConfirm() {
      this.submitAdd();
    },
    handleEditConfirm() {
      this.submitEdit();
    },
    // 获取站点列表
    fetchSites() {
      axios.get('/zsd-merchant/site/list', {
        params: {
          pageSize: 100, // 获取足够多的数据
          status: 1 // 只获取正常营业的站点
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.siteOptions = response.data.data.records;
        } else {
          this.$message.error('获取站点列表失败：' + response.data.msg);
        }
      }).catch(error => {
        console.error('获取站点列表失败', error);
        this.$message.error('获取站点列表失败');
      });
    },

    // 新增 getUserInfo 方法
    getUserInfo() {
      const token = localStorage.getItem('token');
      if (!token) {
        return null;
      }
      // 这里简化为直接返回 adminId 和 role，实际应用中需要解析 token 获取具体信息
      return {
        adminId: 'parsedAdminId', // 示例值，实际应解析 token 获取
        role: 2 // 示例值，实际应解析 token 获取
      };
    },

    // 新增 afterLogin 方法
    afterLogin() {
      const userInfo = this.getUserInfo();
      if (userInfo && userInfo.role === 2) {
        this.fetchAdminsBySiteAndRole(userInfo.adminId, 3);
      } else {
        this.searchAdminInfo(); // 其他角色走原方法
      }
    },

    // 新增 fetchAdminsBySiteAndRole 方法
    fetchAdminsBySiteAndRole(adminId, role) {
      axios.get('/zsd-permission/admin-info/getAdminsByAdminIdAndRole', {
        params: {
          adminId,
          role
        },
        headers: {
          'token': localStorage.getItem('token')
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.adminInfoList = response.data.data; // 假设响应数据结构为 List«管理员信息»
        } else {
          this.$message.error(response.data.msg || '查询失败');
        }
      }).catch(error => {
        console.error('查询失败', error);
        this.$message.error('查询失败');
      });
    }
  },
  created() {
    this.afterLogin(); // 登录后处理
    this.fetchSites(); // 获取站点列表
  }
};
</script>

<style scoped>
.admin-info {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.admin-table {
  width: 100% !important;
  margin: 20px 0;
}

.admin-table .el-table__body {
  width: 100% !important;
}

.admin-table .el-table__header-wrapper,
.admin-table .el-table__body-wrapper {
  width: 100% !important;
}

/* 表格单元格内容样式 */
.admin-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 10px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.el-dialog__body {
  padding: 20px 40px;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 响应式布局调整 */
@media screen and (max-width: 1200px) {
  .admin-table .el-button {
    padding: 8px 12px;
    font-size: 12px;
  }
}

@media screen and (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
  }

  /* 在小屏幕上优化表格显示 */
  .admin-info {
    padding: 10px;
  }

  .admin-table {
    overflow-x: auto;
  }
}
</style>
